package com.swxc.smartorder.ui.activity

import android.os.Bundle
import android.view.View
import com.google.gson.reflect.TypeToken
import com.jaeger.library.StatusBarUtil
import com.lzy.okgo.model.HttpParams
import com.swxc.smartorder.R
import com.swxc.smartorder.app.ConfigSPS
import com.swxc.smartorder.app.GlobalAPI
import com.swxc.smartorder.entity.CommonData
import com.swxc.smartorder.entity.TokenData
import com.swxc.smartorder.entity.UserEntity
import com.swxc.smartorder.event.EventUtil
import com.swxc.smartorder.event.SimpleEvent
import com.swxc.smartorder.network.NetworkHelper
import com.swxc.smartorder.ui.base.BaseActivity
import com.swxc.smartorder.utils.AppSharePreferenceMgr
import com.swxc.smartorder.utils.JsonUtil
import com.swxc.smartorder.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_login.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 登录页面
 */
class LoginActivity : BaseActivity(), View.OnClickListener {
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_login -> {
                login()
            }
            R.id.tv_forget_password -> {
                readyGo(ForgetPwdActivity::class.java)
            }
        }
    }

    private var mobile: String? = null
    private var mHelper: NetworkHelper? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        EventUtil.getInstance().register(this)
        StatusBarUtil.setColor(this, resources.getColor(R.color.ui_gray), 0)

        initViewAndEvent()
    }

    private fun initViewAndEvent() {
        mHelper = NetworkHelper(mContext, supportFragmentManager)
        btn_login.setOnClickListener(this)
        tv_forget_password.setOnClickListener(this)
        mobile = AppSharePreferenceMgr.get(mContext, ConfigSPS.USER_ACCOUNT, "") as String?
        edt_account.setText(mobile)


    }

    private fun login() {
        val strPwd = edt_verification.text.toString().trim()
        val strUserName = edt_account.text.toString().trim()
        if (strUserName.isEmpty()) {
            showToastCommon(
                    "请输入用户账号")
            return
        } else if (strPwd.isEmpty()) {
            showToastCommon("请输入用户密码")
            return
        }
        val httpParams = HttpParams()
        httpParams.put("password", strPwd)
        httpParams.put("username", strUserName)

        mHelper?.login(GlobalAPI.login, httpParams, object : NetworkHelper.NetWorkHelperBack {
            override fun requestSuccess(json: String) {
                val type = object : TypeToken<CommonData<TokenData>>() {}.type
                val fromJson = JsonUtil.fromJson<CommonData<TokenData>>(json, type)
                when {
                    fromJson == null -> showToastError("登录失败")
                    fromJson.success -> when (fromJson.responseCode) {
                        1003 -> {
                            AppSharePreferenceMgr.put(mContext, ConfigSPS.USER_ACCOUNT, strUserName)
                            AppSharePreferenceMgr.put(mContext, ConfigSPS.TOKEN, fromJson.data.accessToken)
                            AppSharePreferenceMgr.put(mContext, ConfigSPS.REFRESH_TOKEN, fromJson.data.refreshToken)
                            val params = HttpParams()
                            mHelper?.getRequest(GlobalAPI.userInfo!!, params, object : NetworkHelper.NetWorkHelperBack {
                                override fun requestSuccess(json: String) {


                                    val type = object : TypeToken<CommonData<UserEntity>>() {}.type
                                    val userBean = JsonUtil.fromJson<CommonData<UserEntity>>(json, type)
                                    if (userBean == null) {
                                        showToastError("获取用户信息失败")
                                        return
                                    }
                                    when (userBean.responseCode) {
                                        1001 -> {
                                            val toJson = JsonUtil.toJson(userBean.data)

                                            AppSharePreferenceMgr.put(mContext, ConfigSPS.PUSH_TAG, userBean.data.pushTags)
                                            AppSharePreferenceMgr.put(mContext, ConfigSPS.AVATAR, userBean.data.avatar)
                                            AppSharePreferenceMgr.put(mContext, ConfigSPS.USER_INFO, toJson)
                                            AppSharePreferenceMgr.put(mContext, ConfigSPS.STAFF_ID, userBean.data.staffId)
                                            readyGoThenKill(WorkActivity::class.java)
                                        }


                                    }


                                }

                                override fun requestFail() {}

                            })

                        }
                        else -> {
                            showToastError(fromJson.message)
                        }
                    }
                    else -> {
                        showToastError("登录失败")
                    }

                }
            }

            override fun requestFail() {
            }
        })


    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.MODIFY_PWD) {
            return
        }
        when (simpleEvent.mEventValue) {
            0x0001 -> {
                val toastUtil = ToastUtil(mContext, true, ToastUtil.STATUS_SUCCESS, "修改密码成功")
                toastUtil.show(2500)
            }
        }

    }

    override fun onDestroy() {

        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }
}
